// pages/help/agree.js
var app = getApp();
Page({

    /**
     * 页面的初始数据
     */
    data: {
        time_index:0,
        car_index:0,
        type_index:0,
        dateString: "",
        spot: ['2021/11/6', '2020/8/9', '2020/8/20', '2020/9/12'],
        open:false
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
      console.log(options);
      var wash_id = options.wash_id;
      if(wash_id == undefined){
        app.showModals('参数错误')
      }else{
       // this.getTime(wash_id);
       this.setData({
         wash_id:wash_id
       })
      }
      var car_id = options.car_id;
      if(car_id == undefined){
        app.showModals('参数错误');
        
      }else{
        this.setData({
          car_id:car_id,
          plate:options.plate
        })
      }
        //this.getAgree();
        this.setData({
            platform:app.globalData.platform,
            width:app.globalData.windowWidth,
            height:app.globalData.windowHeight,
            statusBarHeight:app.globalData.statusBarHeight,
            navHeight:app.globalData.navHeight,
            marginTop:app.globalData.navTitleTop,
            domain:app.globalData.domain
          })
    },
    goBack(){
        wx.navigateBack();
      },
    
    goto:function(e){
      console.log(e);
      var url=e.currentTarget.dataset.url;
      var index=e.currentTarget.dataset.index;
      app.goto(url,index)
  },
 getTime(wash_id,year,month,day){
     let that = this;
     wx.request({
       url: app.globalData.domain+'wechat/wash/getorderTime',
       data:{wash_id:wash_id,year,month,day},
       success:res=>{
//console.log(res);
          let data = res.data;
          if(res.statusCode == 200){
            that.setData({
              list:data.list,
             // status:data.status,
              limit:data.limit,
             // orderNum:data.orderNum
            })
          }
       }
     })
 },
 selectTime(e){
   var index = e.currentTarget.dataset.index;
   var status = e.currentTarget.dataset.status;
   if(status==1){
    this.setData({ids:index})
   }
 },
 saveOrder(){
  let that = this;
  let data = this.data;
  var car_id = data.car_id;
  var plate = data.plate;

  if(car_id==0){
    app.showModals('请选择车辆','#','#');
    return;
  }
  let open = wx.getStorageSync('open');
 
  var plate = data.plate;
  var  wash_id = data.wash_id;
 // var type_index = data.type_index;
  if(wash_id==0){
    app.showModals('选择洗车类型','#','#');
    return;
  }
 
  var selectDay = data.selectDay;
  var ids = data.ids; 
  if(ids==null){
    app.showModals('选择预约时间段','#','#');
    return;
  }
  var list = data.list;
  var time = list[ids].time
  wx.request({
    url:app.globalData.domain + 'wechat/wash/saveWashOrder',
    data:{
      form:'washOrder',
      open_id:open.id,
      openid:open.openid,
      plate:plate,
      car_id:car_id,
      type_id:wash_id,
      date:selectDay.year+'-'+selectDay.month+'-'+selectDay.day,
      time:time,
      desc:''
    },
    success:res=>{
      console.log(res);
      var data=res.data;
      if(res.statusCode==200){
        app.showModals(data.msg,data.url,data.index);
        if(data.code==200){
          that.subScribe(data.order_id);
        }
       
      }else{
        app.showModals('系统错误','#','#')
      }
    }
  })
},
subScribe(order_id){
  var tmplIds =  ['AmeuzYKJ3bdmbpvwKxi_Jn6G-FEQhIAClTwYT8JYx-c','-8LNnstVbH87BVuXhcPkczabxOoPszP0DEO4HqunCEg','klvXk-7gDyxHACuROuTsHPz_WhC3htFMHNxlw5I2Nws'];
  let open = wx.getStorageSync('open');
  wx.requestSubscribeMessage({
    tmplIds:tmplIds,
    success:res=>{
     console.log(res);
      wx.request({
        url:app.globalData.domain + 'wechat/wash/subScribe',
        data:{
          open_id:open.id,
          openid:open.openid,
          order_id:order_id,
          tmplIds:JSON.stringify(tmplIds),
          from:'washorder'
        },
        success:res=>{

        }
      })
    }
  })
},
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    let now = this.data.defaultTime ? new Date(this.data.defaultTime) : new Date();
    var year = now.getFullYear();
    var month = now.getMonth() + 1;
    var day = now.getDate();
    var hour = now.getHours();
    console.log(hour)
    let selectDay = {
      year:year,
      month:month,
      day:day,
      dateString: this.formatTime(now, "Y-M-D")
    }
    console.log(selectDay);
    this.setData({
      selectDay:selectDay
    })
   // this.setMonth(year,month,day);
   this.getTime(this.data.wash_id,year,month,day);
    this.dateInit();
  //this.openChange();
  },


//设置月份
setMonth(setYear, setMonth, setDay) {
  console.log(this.data.selectDay);
  if (this.data.selectDay.year !== setYear || this.data.selectDay.month !== setMonth) {
    const day = Math.min(new Date(setYear, setMonth, 0).getDate(), this.data.selectDay.day)
    const time = new Date(setYear, setMonth - 1, setDay ? setDay : day)
    const data = {
      selectDay: {
        year: setYear,
        month: setMonth,
        day: setDay ? setDay : day,
        dateString: this.formatTime(time, "Y-M-D")
      }
    }
    if (!setDay) {
      data.open = true
    }
    this.setData(data)
    this.dateInit(setYear, setMonth)
    this.setSpot()
    this.triggerEvent("change", this.data.selectDay)
  }
},
//展开收起
openChange() {
  this.setData({
    open: !this.data.open
  })
  this.triggerEvent("aaa", { a: 0 })
  this.dateInit()
  this.setSpot()
},
//设置日历底下是否展示小圆点
setSpot() {
  const timeArr = this.data.spot.map(item => {
    return this.formatTime(item, "Y-M-D")
  })
  this.data.dateList.forEach(item => {
    if (timeArr.indexOf(item.dateString) !== -1) {
      item.spot = true
    } else {
      item.spot = false
    }
  })
  this.setData({
    dateList: this.data.dateList
  })
},
//日历主体的渲染方法
dateInit() {
  let dateList = []; //需要遍历的日历数组数据
//  let now = new Date(setYear, setMonth - 1)//当前月份的1号
 // let startWeek = now.getDay(); //目标月1号对应的星期
///  let dayNum = new Date(setYear, setMonth, 0).getDate() //当前月有多少天
 // let forNum = Math.ceil((startWeek + dayNum) / 7) * 7 //当前月跨越的周数
  if (this.data.open) {
    //展开状态，需要渲染完整的月份
    for (let i = 0; i < forNum; i++) {
      const now2 = new Date(now)
      now2.setDate(i - startWeek + 1)
      let obj = {};
      obj = {
        day: now2.getDate(),
        month: now2.getMonth() + 1,
        year: now2.getFullYear(),
        dateString: this.formatTime(now2, "Y-M-D")
      };
      dateList[i] = obj;
    }
  } else {
    //非展开状态，只需要渲染当前周
    var now2 = new Date();
    console.log(now2);
    var day = now2.getDate();
    var week = [];
    
    for (let i = 0; i < 7; i++) {
     //now2 = now2 + i*24*3600;
     console.log(now2)
      
      now2.setDate(day+i);
      var weeki = new Date(now2).getDay(); 
      week.push(this.getWeek(weeki));
      let obj = {};
      obj = {
        day: now2.getDate(),
        month: now2.getMonth() + 1,
        year: now2.getFullYear(),
        dateString: this.formatTime(now2, "Y-M-D")
      };
      dateList[i] = obj;
    }
  }
  this.setData({
    week:week,
    dateList: dateList
  })
},
getWeek(week){
  var str='';
      if (week == 0) {  
        str = "日";  
    } else if (week == 1) {  
        str = "一";  
    } else if (week == 2) {  
        str = "二";  
    } else if (week == 3) {  
        str = "三";  
    } else if (week == 4) {  
        str = "四";  
    } else if (week == 5) {  
        str = "五";  
    } else if (week == 6) {  
        str = "六";  
    }  
    return str;
},
//一天被点击时
selectChange(e) {
  const year = e.currentTarget.dataset.year
  const month = e.currentTarget.dataset.month
  const day = e.currentTarget.dataset.day
  const dateString = e.currentTarget.dataset.dateString
  const selectDay = {
    year: year,
    month: month,
    day: day,
    dateString: dateString
  }
 this.setData({
   ids:null,
   selectDay:selectDay
 })
  this.getTime(this.data.wash_id,year,month,day);
},
formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
},

getDate(time, format) {
  const formateArr = ['Y', 'M', 'D', 'h', 'm', 's']
  const returnArr = []
  const date = new Date(time)
  returnArr.push(date.getFullYear());
  returnArr.push(this.formatNumber(date.getMonth() + 1));
  returnArr.push(this.formatNumber(date.getDate()));
  returnArr.push(this.formatNumber(date.getHours()));
  returnArr.push(this.formatNumber(date.getMinutes()));
  returnArr.push(this.formatNumber(date.getSeconds()));
  for (const i in returnArr) {
    format = format.replace(formateArr[i], returnArr[i])
  }
  return format;
},

getDateDiff(time) {
  let r = ''
  const ft = new Date(time)
  const nt = new Date()
  const nd = new Date(nt)
  nd.setHours(23)
  nd.setMinutes(59)
  nd.setSeconds(59)
  nd.setMilliseconds(999)
  const d = parseInt((nd - ft) / 86400000)
  switch (true) {
    case d === 0:
      const t = parseInt(nt / 1000) - parseInt(ft / 1000)
      switch (true) {
        case t < 60:
          r = '刚刚'
          break
        case t < 3600:
          r = parseInt(t / 60) + '分钟前'
          break
        default:
          r = parseInt(t / 3600) + '小时前'
      }
      break
    case d === 1:
      r = '昨天'
      break
    case d === 2:
      r = '前天'
      break
    case d > 2 && d < 30:
      r = d + '天前'
      break
    default:
      r = getDate(time, 'Y-M-D')
  }
  return r
},
dateChange(e) {
  this.setData({
    dateString: e.detail.dateString
  })
},
formatTime(time, format) {
     
  if (!format) {
    return this.getDateDiff(time)
  } else {
    return this.getDate(time, format)
  }
},
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})